package com.logic.landseaserver.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.Expenses;
import com.logic.landseaserver.persistence.read.*;
import com.logic.landseaserver.persistence.write.ExpensesWriteMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandeaConstants.CheckType;
import com.logic.landseaserver.common.LandeaConstants.ReRentType;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.BillTypeEnum;
import com.logic.landseaserver.common.enums.RoomStatusCodeEnum;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.domain.CheckList;
import com.logic.landseaserver.domain.Contract;
import com.logic.landseaserver.domain.Room;
import com.logic.landseaserver.persistence.write.CheckFeeListWriteMapper;
import com.logic.landseaserver.persistence.write.CheckListWriteMapper;
import com.logic.landseaserver.service.ICheckListService;
import com.logic.landseaserver.service.IContractService;
import com.logic.landseaserver.service.IProjectAppartment;
import com.logic.landseaserver.ws.dto.CheckFeeListDTO;
import com.logic.landseaserver.ws.dto.CheckListDTO;
import com.logic.landseaserver.ws.dto.CheckListProjectTypeDTO;
import com.logic.landseaserver.ws.dto.ContractDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailDTO;
import com.logic.system.domain.SystemFile;
import com.logic.system.service.impl.FileService;

/**
 * @Author: jack
 * @Date: 2017/6/16
 * @Description: 交割单实现类
 */
@Service
public class CheckListServiceImpl implements ICheckListService
{
    private static final Logger LOG = LoggerFactory.getLogger(CheckListServiceImpl.class);
    
    @Autowired
    private CheckListWriteMapper checkListWriteMapper;
    
    @Autowired
    private CheckListReadMapper checkListReadMapper;
    
    @Autowired
    private IContractService contractServiceImpl;
    
    // @Autowired
    // private ProjectServiceImpl projectServiceImpl;
    
    @Autowired
    private CheckFeeListServiceImpl checkFeeListServiceImpl;
    
    @Autowired
    private CheckFeeListReadMapper checkFeeListReadMapper;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private ProjectReadMapper projectReadMapper;
    
    @Autowired
    private ContractReadMapper contractReadMapper;
    
    @Autowired
    private IProjectAppartment projectAppartmentService;
    
    @Autowired
    private CheckFeeListWriteMapper checkFeeListWriteMapper;

    @Autowired
    private ExpensesReadMapper expensesReadMapper;

    @Autowired
    private ExpensesWriteMapper expensesWriteMapper;

    @Override
    public void delete(String arg0)
        throws BusinessException
    {
        
    }
    
    /**
     * 
     * [描述]：查询交割单信息</br>
     *
     * @param checkListId
     * @return
     *
     */
    @Override
    public CheckListDTO getCheckListDitail(Integer checkListId, Integer checkType)
    {
        Map<String, Object> queryParam = new HashMap<String, Object>();
        queryParam.put("contractId", checkListId);
        queryParam.put("checkType", checkType);
        
        CheckListDTO checkList = checkListReadMapper.getCheckListDetail(queryParam);
        if (null == checkList)
        {
            LOG.info("checkList is null ,contractid is "+checkListId);
            checkList   = new CheckListDTO();
          //  return null;
        }
        
        // 获取费用交割单详情
        List<CheckFeeListDTO> feeList = checkFeeListReadMapper.selectByContractIdAndCheckType(queryParam);
        checkList.setCheckFeeListAll(feeList);

        // 获取入住物品交割单附件图片路径
        List<SystemFile> detailImgs1 = new ArrayList<>();
        if (null != checkList.getCheckinFiles() && !"".equals(checkList.getCheckinFiles()))
        {
            try
            {
                for (String imgid1 : checkList.getCheckinFiles().split(","))
                {
                    SystemFile img1 = (SystemFile)fileService.get(imgid1);
                    detailImgs1.add(img1);
                }
                checkList.setCheckinFilesImgs(detailImgs1);
            }
            catch (BusinessException e)
            {
                LOG.error("getCheckListDitail error.", e);
            }
        }
        
        // 获取退房物品交割单附件图片路径
        List<SystemFile> checkOutImages = new ArrayList<>();
        if (null != checkList.getCheckoutFiles() && !"".equals(checkList.getCheckoutFiles()))
        {
            try
            {
                for (String imgid2 : checkList.getCheckoutFiles().split(","))
                {
                    SystemFile img2 = (SystemFile)fileService.get(imgid2);
                    checkOutImages.add(img2);
                }
                checkList.setCheckoutFilesImgs(checkOutImages);
            }
            catch (BusinessException e)
            {
                LOG.error("getCheckListDitail error.", e);
            }
        }
        
        // 获取朗诗寓社区公约附件图片路径
        List<SystemFile> conventionImages = new ArrayList<>();
        if (null != checkList.getConventionFiles() && !"".equals(checkList.getConventionFiles()))
        {
            try
            {
                for (String imgid3 : checkList.getConventionFiles().split(","))
                {
                    SystemFile img3 = (SystemFile)fileService.get(imgid3);
                    conventionImages.add(img3);
                }
                checkList.setConventionFilesImgs(conventionImages);
            }
            catch (BusinessException e)
            {
                LOG.error("getCheckListDitail error.", e);
            }
        }
        
        return checkList;
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {LandseaException.class, BusinessException.class,
        Exception.class})
    public int insertCheckList(CheckListDTO checkListDTO)
        throws BusinessException, LandseaException
    {
        int activityInt = 0;
        if (this.checkValue(checkListDTO.getContractId(), checkListDTO.getCheckType()))
        {
            CheckList checkList = new CheckList();
            setCheckListByCheckListDTO(checkList, checkListDTO);
            checkList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
            checkListWriteMapper.insertSelective(checkList);
            
            Contract contract = contractReadMapper.selectByPrimaryKey(checkListDTO.getContractId());
            if (null == contract)
            {
                throw LandseaException.createException(LandseaErrorMessageEnum.DELETE_CONTRACT_CONTRACT_IS_NULL);
            }
            
            // 获取入住日期
            Date inDate = contract.getInDate();
            long inDateLong = inDate.getTime();
            
            // 先删除之前的
            // 因为是新增，为了防止重复插入，先删除再新增
            checkFeeListWriteMapper.deleteCheckFeeList(checkListDTO.getContractId(), CheckType.IN_COMING);
            
            // 插入费用交割单
            if (checkListDTO.getCheckFeeListAll().size() > 0)
            {
                List<CheckFeeListDTO> cList = checkListDTO.getCheckFeeListAll();
                for (int i = 0; i < cList.size(); i++)
                {
                    CheckFeeListDTO cfl = new CheckFeeListDTO();
                    CheckFeeListDTO checkDTO = cList.get(i);
                    cfl.setContractId(checkDTO.getContractId());
                    cfl.setType(checkDTO.getType());
                    cfl.setConsumptionEnd(checkDTO.getConsumptionEnd());
                    
                    Date time = checkDTO.getInDate();
                    
                    if (null == time || inDateLong > time.getTime())
                    {
                        throw LandseaException.createException(LandseaErrorMessageEnum.CHECK_LIST_DATE_EROR);
                    }
                    
                    cfl.setInDate(checkDTO.getInDate());
                    cfl.setCheckType(checkList.getCheckType());
                    int id = checkFeeListServiceImpl.insertCheckFeeList(cfl);
                    checkDTO.setId(id);
                }
                
                // 将房间状态改为已出租
                Room dsRoom = new Room();
                dsRoom.setId(contract.getRoomId());
                dsRoom.setAppendStatus(RoomStatusCodeEnum.LRB3.getCode());
                projectAppartmentService.updateAppendStatus(dsRoom);
            }
        }
        else
        {
            activityInt = 7010001;
        }
        return activityInt;
    }
    
    // 根据合同编号获取类型
    @Override
    public List<CheckListProjectTypeDTO> getProIdByContract(int contractId)
    {
        ContractDTO contractDTO = null;
        try
        {
            contractDTO = (ContractDTO)contractServiceImpl.get(contractId);
        }
        catch (BusinessException e)
        {
            LOG.error("getProIdByContract error.", e);
        }
        // ProjectDetailDTO projectDetailDTO = projectServiceImpl.getProjectDetail(contractDTO.getPdfId());
        ProjectDetailDTO projectDetailDTO = projectReadMapper.getProjectDetail(contractDTO.getProjectId());
        String cost = projectDetailDTO.getCostType();
        List<CheckListProjectTypeDTO> cptdList = new ArrayList<>();
        for (String imgid3 : cost.split(","))
        {
            // COTY1 COTY2 COTY3 COTY4
            if (BillTypeEnum.CTBI1.getCode().equals(imgid3) || BillTypeEnum.CTBI2.getCode().equals(imgid3)
                || BillTypeEnum.CTBI3.getCode().equals(imgid3) || BillTypeEnum.CTBI4.getCode().equals(imgid3))
            {
                CheckListProjectTypeDTO cptd = new CheckListProjectTypeDTO();
                cptd.setTypeValue(imgid3);
                // cptd.setTypeName(null);
                if (BillTypeEnum.CTBI1.getCode().equals(imgid3))
                {
                    cptd.setTypeName("水费");
                }
                else if (BillTypeEnum.CTBI2.getCode().equals(imgid3))
                {
                    cptd.setTypeName("电费");
                }
                else if (BillTypeEnum.CTBI3.getCode().equals(imgid3))
                {
                    cptd.setTypeName("燃气费");
                }
                else if (BillTypeEnum.CTBI4.getCode().equals(imgid3))
                {
                    cptd.setTypeName("热水费");
                }
                cptdList.add(cptd);
            }
        }
        
        return cptdList;
    }
    
    @Override
    public int insert(Object arg0)
        throws BusinessException
    {
        return 0;
    }
    
    @Override
    public List<?> query(QueryUtil arg0)
    {
        return null;
    }
    
    @Override
    public void update(Object arg0)
        throws BusinessException
    {
        
    }
    
    @Override
    public Boolean validate(Object o)
        throws BusinessException
    {
        return null;
    }
    
    public Boolean checkValue(Integer checkListId, Integer checkType)
        throws BusinessException
    {
        boolean retValue = false;
        
        Map<String, Object> queryParam = new HashMap<String, Object>();
        queryParam.put("contractId", checkListId);
        queryParam.put("checkType", checkType);
        
        CheckListDTO checkList = checkListReadMapper.getCheckListDetail(queryParam);
        if (null != checkList && !"".equals(checkList))
        {
            return retValue;
            // throw new LandseaBusinessException(LandseaErrorMessageEnum.CHECKLIST_DUPLICATED);
        }
        retValue = true;
        return retValue;
    }
    
    @Override
    public Boolean validateForDelete(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public Boolean validateForInsert(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public Boolean validateForUpdate(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {LandseaException.class, BusinessException.class,
        Exception.class})
    public void editCheckList(CheckListDTO checkListDTO)
        throws BusinessException, LandseaException
    {
        CheckList checkList = checkListReadMapper.selectByPrimaryKey(checkListDTO.getId());
        if(checkList==null){
            checkList = new CheckList();
            setCheckListByCheckListDTO(checkList, checkListDTO);
            checkList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
            checkListWriteMapper.insertSelective(checkList);
        }else{
            setCheckListByCheckListDTO(checkList, checkListDTO);
            checkList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
            checkListWriteMapper.updateByPrimaryKeySelective(checkList);
        }
        Contract contract = contractReadMapper.selectByPrimaryKey(checkListDTO.getContractId());
        if (null == contract)
        {
            throw LandseaException.createException(LandseaErrorMessageEnum.DELETE_CONTRACT_CONTRACT_IS_NULL);
        }
        
        // 获取入住日期
        Date inDate = contract.getInDate();
        long inDateLong = inDate.getTime();
        
        // 如果是转租或者续租，则不能修改时间
        //0417需求 转租后水电等交割单读数支持修改，避免由诗友承担清洁过程中的能耗
        if (contract.getOriginalCId() != null && contract.getRentType().equals(ReRentType.RERENT))
        {
            return;
        }
        List<CheckFeeListDTO> cList = new ArrayList<>();
        // 修改费用交割单
        if (checkListDTO.getCheckFeeListAll().size() > 0)
        {
            cList = checkListDTO.getCheckFeeListAll();
            for (int i = 0; i < cList.size(); i++)
            {
                CheckFeeListDTO cfl = new CheckFeeListDTO();
                CheckFeeListDTO checkDTO = cList.get(i);
                cfl.setId(checkDTO.getId());
                cfl.setContractId(checkDTO.getContractId());
                cfl.setType(checkDTO.getType());
                cfl.setConsumptionEnd(checkDTO.getConsumptionEnd());
                
                Date time = checkDTO.getInDate();

                if (null == time || inDateLong > time.getTime())
                {
                    throw LandseaException.createException(LandseaErrorMessageEnum.CHECK_LIST_DATE_EROR);
                }
                
                cfl.setInDate(checkDTO.getInDate());
                checkFeeListServiceImpl.editCheckFeeList(cfl);
                //0417需求 转租同步修改运营数据
                if (contract.getOriginalCId() != null && contract.getRentType().equals(ReRentType.CHANGE))
                {
                    Expenses expenses = expensesReadMapper.selectExpenseIn(contract.getRoomId(),cList.get(i).getType());
                    if(expenses!=null){
                        //读数不能少于之前同步的读数
                        Double degree = expenses.getDegree();
                        if(expenses.getDegree().compareTo(cList.get(i).getConsumptionEnd())>0){
                            throw new BusinessException(String.format(LandseaErrorMessageEnum.CHECK_FEELIST_DEGREE_EROR.getDesc(), StringTools.getEmunName(cList.get(i).getType())));
                        }
                        //修改运营基础数据
                        expenses.setReadMeterTime(cList.get(i).getInDate());
                        expenses.setDegree(cList.get(i).getConsumptionEnd());
                        expenses.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                        expensesWriteMapper.updateByPrimaryKeySelective(expenses);
                    }
                }
            }
        }
    }
    
    @Override
    public void deleteCheckList(Integer id)
        throws BusinessException
    {
        
    }
    
    // 通过orderDTO创建order
    public void setCheckListByCheckListDTO(CheckList checkList, CheckListDTO checkListDTO)
    {
        if (!StringUtils.isEmpty(checkListDTO.getId()))
        {
            checkList.setId(checkListDTO.getId());
        }
        if (!StringUtils.isEmpty(checkListDTO.getContractId()))
        {
            checkList.setContractId(checkListDTO.getContractId());
        }
        if (!StringUtils.isEmpty(checkListDTO.getCheckinFiles()))
        {
            checkList.setCheckinFiles(checkListDTO.getCheckinFiles());
        }
        if (!StringUtils.isEmpty(checkListDTO.getCheckoutFiles()))
        {
            checkList.setCheckoutFiles(checkListDTO.getCheckoutFiles());
        }
        if (!StringUtils.isEmpty(checkListDTO.getConventionFiles()))
        {
            checkList.setConventionFiles(checkListDTO.getConventionFiles());
        }
        if (!StringUtils.isEmpty(checkListDTO.getComments()))
        {
            checkList.setComments(checkListDTO.getComments());
        }
        if (!StringUtils.isEmpty(checkListDTO.getUserId()))
        {
            checkList.setUserId(checkListDTO.getUserId());
        }
        if (null != checkListDTO.getCheckType())
        {
            checkList.setCheckType(checkListDTO.getCheckType());
        }
    }
    @Override
    public Object get(Integer arg0)
        throws BusinessException
    {
        // TODO Auto-generated method stub
        return null;
    }
    
}
